#import "BWCrossStitchRectangleTool.h"
#import "BWCrossStitchChangeList.h"


@implementation BWCrossStitchRectangleTool

- (void) drawRectFromRow: (int) row1   column: (int) column1
                   toRow: (int) row2   column: (int) column2
              withThread: (BWThread *) thread
{
    // invalidate old change list in view
    [changeList purge];

    int minRow = MIN (row1, row2);
    int maxRow = MAX (row1, row2);
    int minColumn = MIN (column1, column2);
    int maxColumn = MAX (column1, column2);

    int r, c;

    // top and bottom rows
    for (c = minColumn; c <= maxColumn; c++) {
        [changeList addStitchWithThread: thread
                    atRow: startRow
                    column: c];
        [changeList addStitchWithThread: thread
                    atRow: endRow
                    column: c];
    }

    // sidebars
    for (r = minRow; r <= maxRow; r++) {
        [changeList addStitchWithThread: thread
                    atRow: r
                    column: startColumn];
        [changeList addStitchWithThread: thread
                    atRow: r
                    column: endColumn];
    }

    [self invalidateRectAt: row1  column: column1
          row: row2  column: column2];

} // drawRectFromRow


- (void) startDragAtRow: (int) row  
                 column: (int) column
                 thread: (BWThread *) thread
{
    startRow = endRow = row;
    startColumn = endColumn = column;

    [self drawRectFromRow: startRow  column: startColumn
          toRow: endRow  column: endColumn
          withThread: thread];

} // startDragAtRow


- (void) continueDragAtRow: (int) row
                    column: (int) column
                    thread: (BWThread *) thread
{
    [self invalidateRectAt: startRow  column: startColumn
          row: endRow  column:  endColumn];

    if ([self isConstrained]) {
        int rowDelta = abs(startRow - row);
        if (column < startColumn) {
            column = startColumn - rowDelta;
        } else {
            column = startColumn + rowDelta;
        }
    }

    endRow = row;
    endColumn = column;

    [self drawRectFromRow: startRow  column: startColumn
          toRow: endRow  column: endColumn
          withThread: thread];

    [self invalidateRectAt: startRow  column: startColumn
          row: endRow  column:  endColumn];

} // continueDragAtRow


- (NSString *) name
{
    return (@"Draw rectangles with cross stitches");
} // name


@end // BWCrossStitchRectangleTool
